package bg.uni_sofia.conf_manager.beans;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import bg.uni_sofia.conf_manager.model.Company;
import bg.uni_sofia.conf_manager.model.Conference;
import bg.uni_sofia.conf_manager.model.Employee;
import bg.uni_sofia.conf_manager.model.Lecturer;
import bg.uni_sofia.conf_manager.model.TransferEmployee;
/**
 * Session Bean implementation class EmployeeBean
 */

@Stateless
@Path("/employee")
public class EmployeeBean {
	@PersistenceContext
	private EntityManager em;
	@Inject
	LoginBean sesData;

    /**
     * Default constructor. 
     */
    public EmployeeBean() {
    }

	@GET
	@Produces("application/json")
	public List<Employee> getAllEmployees() {
		return em.createNamedQuery("getAllEmployees", Employee.class)
				.getResultList();
	}

	@POST
	@Path("/changeLastLogin")
	@Consumes("application/json")
	public boolean changeLastLogin(String name) {
		TypedQuery<Employee> query = em.createNamedQuery("getEmployeeByName",
				Employee.class);
		query.setParameter("username", name);
		Employee e = query.getResultList().get(0);
		if (e == null) {
			TypedQuery<Lecturer> lecturerQuery = em.createNamedQuery(
					"getLecturerByName", Lecturer.class);
			query.setParameter("username", name);
			Lecturer l = lecturerQuery.getResultList().get(0);
			if (l == null) {
				return false;
			} else {
				l.setLastLogin(new Date());
				em.merge(l);
				return true;
			}
		}
//		System.out.println(e);
		e.setLastLogin(new Date());
		em.merge(e);
		return true;
	}
	
	@GET
	@Path("/getEmployeeConferences")
	@Consumes("application/json")
	public List<Conference> getEmployeeConferences(){
		TypedQuery<Employee> query = em.createNamedQuery("getEmployeeById",
				Employee.class);
		long employeeID = sesData.getId();
		query.setParameter("id", employeeID);
		List<Employee> list = query.getResultList();
		if (list.size() > 0) {
			Employee emp = list.get(0);
			return emp.getConferences();
		} else {
			return null;
		}
	}
	
	@POST
	@Path("/isMineConference")
	@Consumes("application/json")
	public boolean isMineConference(String conferenceName){
		TypedQuery<Employee> query = em.createNamedQuery("getEmployeeById",
				Employee.class);
		long employeeID = sesData.getId();
		query.setParameter("id", employeeID);
		List<Employee> list = query.getResultList();
		if (list.size() > 0) {
			Employee emp = list.get(0);
			List<Conference> confList = emp.getConferences();
			for(Conference conf: confList){
				if(conf.getName().equals(conferenceName)){
					return true;
				}
			}
			return false;
		} else {
			return false;
		}
	}

	@POST
	@Path("/getEmployeeInfoByName")
	@Consumes("application/json")
	public Employee getEmployeeInfoByName(String name){
		TypedQuery<Employee> query = em.createNamedQuery("getEmployeeByName",Employee.class);
		query.setParameter("username", name);
		if (query.getResultList().size()>0){
			return query.getResultList().get(0);
		}
		else{
			return null;
		}
	}
	
	@POST
	@Consumes("application/json")
	public Employee addEmployee(TransferEmployee transferEmp) {
		Employee existingEmployee = getEmployeeInfoByName(transferEmp.getUsername());
		if (existingEmployee == null) {
			TypedQuery<Company> query = em.createNamedQuery("getCompanyByName",
					Company.class);
			query.setParameter("companyName", transferEmp.getCompanyName());

			Company comp = null;
			if (query.getResultList().size() > 0) {
				comp = query.getResultList().get(0);
			} else {
				System.out.println("no employee inserted");
			}
			try {
				existingEmployee = new Employee(transferEmp.getUsername(), hashPassword(transferEmp.getPassword()), transferEmp.getEmail(), transferEmp.getName(), comp, true, new Date());
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			comp.addEmployee(existingEmployee);
			em.persist(existingEmployee);
			em.merge(comp);
			return existingEmployee;
		} else {
			return null;
		}



	}
	
public String hashPassword(String password) throws NoSuchAlgorithmException{
		
		MessageDigest md = MessageDigest.getInstance("SHA-1");
		md.update(password.getBytes());
		byte byteData[] = md.digest();
		return new String(bytesToHex(byteData));

	}
	
	public static String bytesToHex(byte[] b) {
	      char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7',
	                         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
	      StringBuffer buf = new StringBuffer();
	      for (int j=0; j<b.length; j++) {
	         buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
	         buf.append(hexDigit[b[j] & 0x0f]);
	      }
	      return buf.toString();
	   }

}
